from django.conf import settings
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet
from rest_framework.permissions import IsAdminUser
from fdfs_client.client import Fdfs_client

from goods.models import SKUImage, SKU
from meiduo_admin.serializers.images import ImagesSerializer, SKUserializer
from meiduo_admin.utils import PageNum

class ImagesView(ModelViewSet):

    queryset = SKUImage.objects.all()
    serializer_class = ImagesSerializer
    pagination_class = PageNum

    # 添加验证，以前也都应该加
    permission_classes = [IsAdminUser]

    def simple(self, request):
        """
        获取商品SKU信息
        :param request:
        :return:
        """
        # 1 查询所有sku商品
        skus = SKU.objects.all()

        # 2 序列化返回
        ser = SKUserializer(skus, many=True)
        return Response(ser.data)

    # def create(self, request, *args, **kwargs):  封装到序列化器中了
    #     # 1 获取前端数据
    #     data  = request.data
    #
    #     # 2 验证数据
    #     ser = self.get_serializer(data=data)
    #     ser.is_valid()
    #
    #     # # 3 建立fastdfs客户端
    #     # client = Fdfs_client(settings.FASTDFS_PATH)
    #     # file = request.FILES.get('image')
    #     #
    #     # # 4 上传图片
    #     # # res = client.upload_by_buffer(file)  因为读取的是二进制数据，所以需要下面那种形式才能读到
    #     # res = client.upload_by_buffer(file.read())
    #     #
    #     # # 5 判断是否上传成功
    #     # if res['Status'] != 'Upload successed.':
    #     #     return Response({'error': '图片上传失败'})
    #     #
    #     # # 6 保存图片表
    #     # img = SKUImage.objects.create(sku_id=ser.validated_data['sku'].id, image=res['Remote file_id'])
    #     # # img = SKUImage.objects.create(sku=ser.validated_data['sku'], image=res['Remote file_id'])
    #
    #     # 7 返回保存后的数据图片
    #
    #
    #     # return Response({
    #     #     'id': img.id,
    #     #     'sku': img.sku_id,
    #     #     'image': img.image.url
    #     # })
    #
    #     ser.save()
    #     return Response(ser.data, status=201)
